﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using SharePhone.Common;
using SharePhone.Core.UserProfile;
using SharePhone.Provider.WebServices;

namespace SharePhone.Provider
{
    public delegate void UserProfileLoaded(UserProfile profile);

    public delegate void UserProfileUpdated(RequestCompleteEventArgs result);

    public delegate void PropertyChoiceListLoaded(List<string> choices);

    public class UserProfileProvider
    {
        public static void GetUserProfile(string accountName, UserProfileLoaded callback, string spUrl,
                                          CredentialSettings credentials)
        {
            var client = new SPUserProfileService(spUrl, credentials);
            client.GetUserProfileByNameCompleted += (object sender, RequestCompleteEventArgs e) =>
                                                        {
                                                            if (!e.Cancelled)
                                                            {
                                                                var profile = new UserProfile();
                                                                var serializer = new XmlSerializer(
                                                                    typeof (PropertyData),
                                                                    "http://microsoft.com/webservices/SharePointPortalServer/UserProfileService");

                                                                profile.Properties =
                                                                    new ObservableCollection<PropertyData>();
                                                                foreach (
                                                                    XElement element in
                                                                        e.Result.Descendants(XName.Get("PropertyData",
                                                                                                       "http://microsoft.com/webservices/SharePointPortalServer/UserProfileService"))
                                                                    )
                                                                {
                                                                    var property =
                                                                        (PropertyData)
                                                                        serializer.Deserialize(element.CreateReader());
                                                                    profile.Properties.Add(property);
                                                                }
                                                                callback(profile);
                                                            }
                                                            else
                                                                throw new Exception(
                                                                    string.Format("Error retrieving user profile: {0}",
                                                                                  e.ErrorDescription), e.Error);
                                                        };
            client.GetUserProfileByNameAsync(accountName);
        }

        //public static void GetPropertyChoiceValues(string propertyName, PropertyChoiceListLoaded callback, string spUrl, CredentialSettings credentials) {
        //    UserProfileServiceSoapClient client = ServiceFactory.GetUserProfileService(spUrl, credentials);
        //    client.GetPropertyChoiceListCompleted += (object sender, GetPropertyChoiceListCompletedEventArgs e) => {
        //        callback(e.Result.ToList());
        //    };
        //    client.GetPropertyChoiceListAsync(propertyName);
        //}
        public static void UpdateUserProfile(UserProfile profile, UserProfileUpdated callback, string spUrl,
                                             CredentialSettings credentials)
        {
            var client = new SPUserProfileService(spUrl, credentials);
            var serializer = new XmlSerializer(typeof (PropertyData[]),
                                               "http://microsoft.com/webservices/SharePointPortalServer/UserProfileService");
            var doc = new XDocument();
            XmlWriter writer = doc.CreateWriter();
            serializer.Serialize(writer, profile.Properties.Where(p => p.IsValueChanged).ToArray());
            writer.Close();
            var innerXml = new StringBuilder();
            IEnumerable<XElement> updatedProperties =
                doc.Descendants(XName.Get("PropertyData",
                                          "http://microsoft.com/webservices/SharePointPortalServer/UserProfileService"));
            foreach (XElement property in updatedProperties)
                innerXml.Append(property.ToString());
            client.ModifyUserPropertyByAccountNameAsync(profile.AccountName, innerXml.ToString());
            client.ModifyUserPropertyByAccountNameCompleted +=
                (object sender, RequestCompleteEventArgs e) => { callback(e); };
        }


        //private static UserProfile ParseProperties(ObservableCollection<PropertyData> profileProperties) {
        //    UserProfile profile = new UserProfile();
        //    profile.Properties = profileProperties;
        //    return profile;
        //}
    }
}